package de.mp3player.app;

import java.io.*;
import java.util.Map;

import javax.sound.sampled.*;

import org.tritonus.share.sampled.TAudioFormat;
import org.tritonus.share.sampled.file.TAudioFileFormat;

public class MPlayer {
	
	private File file;
	
	public MPlayer(File file){
		this.file = file;
	}

	public void play(){
	  try {
	    AudioInputStream in= AudioSystem.getAudioInputStream(file);
	    AudioInputStream din = null;
	    AudioFormat baseFormat = in.getFormat();
	    AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
	                                                baseFormat.getSampleRate(),
	                                                16,baseFormat.getChannels(),
	                                                baseFormat.getChannels() * 2,
	                                                baseFormat.getSampleRate(),false);
	    din = AudioSystem.getAudioInputStream(decodedFormat, in);
	    rawplay(decodedFormat, din);
	    in.close();
	  } catch (Exception e){}
	}
	private void rawplay(AudioFormat targetFormat, AudioInputStream din) throws IOException, LineUnavailableException{
	  byte[] data = new byte[4096];
	  SourceDataLine line = getLine(targetFormat);
	  if (line != null){
	    line.start();
	    int nBytesRead = 0, nBytesWritten = 0;
	    while (nBytesRead != -1){
	        nBytesRead = din.read(data, 0, data.length);
	        if (nBytesRead != -1) nBytesWritten = line.write(data, 0, nBytesRead);
	    }
	    line.drain();
	    line.stop();
	    line.close();
	    din.close();
	  }
	}

	private SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException{
	  SourceDataLine res = null;
	  DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
	  res = (SourceDataLine) AudioSystem.getLine(info);
	  res.open(audioFormat);
	  return res;
	}
	public void getMP3Info() throws UnsupportedAudioFileException, IOException{
		AudioFileFormat baseFileFormat = null;
		AudioFormat baseFormat = null;
		baseFileFormat = AudioSystem.getAudioFileFormat(file);
		baseFormat = baseFileFormat.getFormat();
		if (baseFileFormat instanceof TAudioFileFormat){
		    Map properties = ((TAudioFileFormat)baseFileFormat).properties();
		    String key = "author";
		    String val = (String) properties.get(key);
		    key = "mp3.id3tag.v2";
		    InputStream tag= (InputStream) properties.get(key);
		}
		if (baseFormat instanceof TAudioFormat){
		     Map properties = ((TAudioFormat)baseFormat).properties();
		     String key = "bitrate";
		     Integer val = (Integer) properties.get(key);
		}
	}
}